<?php
use \GatewayWorker\Lib\Gateway;


class match extends cmdbase
{
	public static $MaxNum = 8;
	public function onCmd($msg){
		$group_mgr = $GLOBALS['GroupMgr'];
		$group_id = $msg['room_id'];
		if($group_id == -1){
			$group_id = $group_mgr->createGroupId();
		}else if ($group_id == -2) {
			$group_id = $this->getMatchingGroupId();
			if(!isset($group_id)){
				$msg_body = array(
		            'ret'=> NetErrorCode::$Error,
		            "room_id" => -2,
		            'reason'=>"没有空闲的房间",
		        );
		 		return $msg_body;
			}
		}else{
			//找不到房间，需要报错给客户端
			$client_count = Gateway::getClientCountByGroup($group_id);
			if($client_count < 1){
				$msg_body = array(
		            'ret'=> NetErrorCode::$Error,
		            "room_id" => $group_id,
		            'reason'=>"房间已丢失",
		        );
		 		return $msg_body;
			}else if($client_count > static::$MaxNum - 1){
				$msg_body = array(
		            'ret'=> NetErrorCode::$Error,
		            "room_id" => $group_id,
		            'reason'=>"房间人数已满",
		        );
		 		return $msg_body;
			}else if($group_mgr->isBattle($group_id)){
				$msg_body = array(
		            'ret'=> NetErrorCode::$Error,
		            "room_id" => $group_id,
		            'reason'=>"暂不支持进入已开始的房间",
		        );
		 		return $msg_body;
			}
		}

		//加入组
		$client_id = $this->getCurClientId();
		$group_mgr->joinGroup($client_id, $group_id);

		//广播
		$user_id = Gateway::getUidByClientId($client_id);
		$this->sendToGroup("notify_enterroom", array('uid'=>$user_id,'num' => Gateway::getClientCountByGroup($group_id)));

 		$msg_body = array(
            'ret'=> NetErrorCode::$None,
            "room_id" => $group_id,
            //'reason'=>"success",
        );
 		return $msg_body;
	}

	//返回一个正在匹配的房号
	private function getMatchingGroupId(){
		$group_id_list = Gateway::getAllGroupIdList();
		foreach ($group_id_list as $group_id) {
			$group_mgr = $GLOBALS['GroupMgr'];
			if($group_mgr->isBattle($group_id) || Gateway::getClientCountByGroup($group_id) > static::$MaxNum - 1){
				continue;
			}
			return $group_id;
		}
	}
}